package com.example.yang.yixin.Activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.Toast;

import com.example.yang.yixin.R;
import com.example.yang.yixin.Utils.UserUtils;
import com.example.yang.yixin.Views.InputView;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.util.ArrayList;
import java.util.List;

import static java.net.SocketOptions.SO_TIMEOUT;

public class LoginActivity extends BaseActivity {
private InputView minputphone,minputpassword;
    private SharedPreferences pref;
    private SharedPreferences.Editor editor;
    private CheckBox rememberpass;
    private String responseMsg = "";
    private static final int REQUEST_TIMEOUT = 5*1000;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        init();
        minputphone=fd(R.id.input_number);
        minputpassword=fd(R.id.input_password);
        rememberpass=fd(R.id.rememberpass);
        pref=getSharedPreferences("user",MODE_PRIVATE);
        boolean isremember=pref.getBoolean("rememberpass",false);
        if(isremember){
            String UserName=pref.getString("inputphone","");
            String Password=pref.getString("inputpassword","");
            minputphone.setText(UserName);
            minputpassword.setText(Password);
            rememberpass.setChecked(true);
        }


    }
    private void init(){
        initNarvBar(false,"登录",false);
    }
    public void OnRegisterClick(View v){
        Intent intent=new Intent(LoginActivity.this,RegisterActivity.class);
        startActivity(intent);

    }
    public void OnCommitClick(View v){
        Thread loginThread = new Thread(new LoginThread());
        loginThread.start();


    }



    public void OnForgetClick(View view) {
        Snackbar.make(view,"请联系管理员qq:2460228341",Snackbar.LENGTH_SHORT).setAction("我知道了", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                minputpassword.setText("");
            }
        }).show();
    }
    private boolean loginServer(String username, String password)
    {
        boolean loginValidate = false;
        //使用apache HTTP客户端实现
        String urlStr = "http://47.106.141.161/MyFirstAndroidApp/LoginServlet";
        HttpPost request = new HttpPost(urlStr);
        //如果传递参数多的话，可以对传递的参数进行封装
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        //添加用户名和密码
        params.add(new BasicNameValuePair("username",username));
        params.add(new BasicNameValuePair("password",password));
        try
        {
            //设置请求参数项
            request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            HttpClient client = getHttpClient();
            //执行请求返回相应
            HttpResponse response = client.execute(request);

            //判断是否请求成功
            if(response.getStatusLine().getStatusCode()==200)
            {
                loginValidate = true;
                //获得响应信息
                responseMsg = EntityUtils.toString(response.getEntity());
            }
        }catch(Exception e)
        {
            e.printStackTrace();
        }
        return loginValidate;
    }
    public HttpClient getHttpClient()
    {
        BasicHttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);
        HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
        HttpClient client = new DefaultHttpClient(httpParams);
        return client;
    }

    //Handler
    Handler handler = new Handler()
    {
        public void handleMessage(Message msg)
        {
            switch(msg.what)
            {
                case 1:
                    Snackbar.make(getWindow().getDecorView(),"你输入的密码错误哦",Snackbar.LENGTH_SHORT).setAction("重新输入", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            minputpassword.setText("");
                        }
                    }).show();
                    break;
                case 2:
                    Snackbar.make(getWindow().getDecorView(),"好像没有网络哦！",Snackbar.LENGTH_SHORT).setAction("检查网络", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                        }
                    }).show();
                    break;

            }

        }
    };
    class LoginThread implements Runnable
    {

        @Override
        public void run() {
            String number=minputphone.getInputStr();
            String password=minputpassword.getInputStr();
            //URL合法，但是这一步并不验证密码是否正确
            boolean loginValidate = loginServer(number, password);
            Message msg=handler.obtainMessage();


            if(loginValidate)
            {
                if(responseMsg.equals("true")){
                    editor=pref.edit();
                    if(rememberpass.isChecked()){
                        editor.putBoolean("rememberpass",true);
                        editor.putString("inputphone",number);
                        editor.putString("inputpassword",password);
                    }else {
                        editor.clear();
                    }
                    editor.apply();
                    Intent intent1=new Intent();
                    intent1.putExtra("data",number);
                    intent1.setClass(LoginActivity.this,MainActivity.class);
                    startActivity(intent1);
                    finish();
                }else if (responseMsg.equals("false"))
                {
                    msg.what = 1;
                    handler.sendMessage(msg);
                }

            }else
            {
                msg.what=2;
                handler.sendMessage(msg);
            }
        }

    }
}
